import Cp from "crypto-js";

let BaseUrl = "http://101.36.122.116:8000/";

const request = async (params: any,requestTitle:string) => {
    const query = [];
    for (const k in params) {
        query.push(`${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`);
    }
    const url = `${BaseUrl+requestTitle}?${query.join('&')}`;
    console.log('【群聊接口】'+url);//TODO 2021-03-07
    const response = await fetch(url);
    return response.json();
};
//获取地址的群聊天列表
export const getGroupList = async (address: string) => {
    let res = await request({address:address}, "getgrouplist")
    return res;
}

//
export const joinGroup = async (address: string,creator:string,desc:string,key:string,addressout:string,voucher:string) => {
    let res = await request({address:address,creator,desc,key,addressout,voucher}, "joingroup")
    return res;
}

export const getGroupMember = async (addressout: string) => {
    let res = await request({addressout:addressout}, "getgroupmember")
    return res;
}

export const enAES = (seed:string,data:string) => {
    var key  = Cp.enc.Utf8.parse(seed);
    var srcs = Cp.enc.Utf8.parse(data);
    var encrypted = Cp.AES.encrypt(srcs, key, {mode:Cp.mode.ECB,padding: Cp.pad.Pkcs7});
    let res =  encrypted.toString();
    return res;
}

export const deAES = (seed:string,data:string) =>{
    try {
        var key = Cp.enc.Utf8.parse(seed);
        var decrypt = Cp.AES.decrypt(data, key, {mode: Cp.mode.ECB, padding: Cp.pad.Pkcs7});
        return Cp.enc.Utf8.stringify(decrypt).toString();
    } catch (e) {
        return data;
    }
}
